package com.lej.home

import android.content.Intent
import android.net.Uri
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.widget.AppCompatImageView
import androidx.core.view.isInvisible
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.lej.core.base.BaseActivity
import com.lej.core.common.ORIENTATION_PORTRAIT
import com.lej.core.common.PCacheInfo
import com.lej.core.common.Params
import com.lej.core.common.userIsLogin
import com.lej.core.dsl.*
import com.lej.core.provider.pushProvider
import com.lej.core.provider.unityProvider
import com.lej.core.router.CRouter
import com.lej.core.utils.DevicesUtils.isLow6GConfiguration
import com.lej.core.utils.DevicesUtils.isLowConfiguration
import com.lej.core.utils.changeQiniuSize
import com.lej.core.utils.extention.*
import com.lej.core.utils.load
import com.lej.dataservice.club.bean.main.home.*
import com.lej.dataservice.club.http.NetworkUtil
import com.lej.dataservice.club.http.bean.ResStatus
import com.lej.dataservice.club.http.bean.onSuccess
import com.lej.home.databinding.*
import com.lej.home.player.PlayerActivity
import com.lej.home.view.MoveView
import com.lej.theme.dialog.CommonDialog
import com.lej.theme.dialog.HorAlertPopDialog
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.AttachPopupView
import com.lxj.xpopup.core.CenterPopupView
import com.qmuiteam.qmui.kotlin.onClick
import com.qmuiteam.qmui.util.QMUIDisplayHelper
import com.qmuiteam.qmui.util.QMUIStatusBarHelper
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import kotlin.math.max

@Route(path = CRouter.newMain)
class HHomeActivity : BaseActivity<HomeFragmentHome2Binding, HomeViewModel>() {
    companion object {
        private const val T_LIVE = 1//直播
        private const val T_NFT_WALL = 2//照片墙
        private const val T_NFT = 20//nft单个藏品
        private const val T_WALL_START = 21//照片墙start
        private const val T_WALL_CONTENT = 22//照片墙
        private const val T_WALL_END = 23//照片墙end
        private const val T_BOOTH = 3//展位
        private const val T_BOOTH_START = 31//展位start
        private const val T_BOOTH_CONTENT = 32//展位
        private const val T_BOOTH_END = 33//展位end
        private const val T_BANNER = 4//广告banner
        private const val T_SPACE = 90//占位
        private const val T_START = 91//开始
        private const val T_END = 92//结束
        private const val T_CLICK_CHECK = 93//第一层点击事件监听

        private const val BANNER_TYPE_LINK = 1 //banner 链接类型
        private const val BANNER_TYPE_SPACE = 2 //banner空间类型
    }

    override fun getLayout(): Int = R.layout.home_fragment_home2

    override fun initVariableId(): Int = BR.vm

    private var isSkip = false

    //region 计算宽度
    private val startW get() = screenH * 2.5f / 8f//开始标签的宽度
    private val liveW get() = screenH * 307f / 150f//live宽度
    private val wallW get() = screenH * 0.88f * 2420f / 800f//个人空间宽度
    private val nftW get() = 300f//单个nft宽度
    private val bannerW get() = screenH * 0.886f * 1608f / 800f//广告banner宽度
    private val endW get() = screenH * 554f / 1238f//end宽度

    private val leftLive get() = 0.25f * screenH//live左边阴影偏移
    private val leftWall get() = 0.34f * screenW//个人空间左边偏移
    private val leftNft get() = 0.48f * screenW//nft左边向右
    private val leftBooth get() = 0.6f * screenW//booth向左
    private val leftBanner get() = 0.2f * screenW//banner向左
    private fun BoothInfo.getBoothW(): Float {//展台宽度
        var size = 0.5f.scp
        boothList?.forEach {
            val radio = if (it.h == 0) 1 else it.w / it.h
            size += (40f + max(0.4f.scp.toInt() * radio, 156))
        }
        return size
    }
    //endregion

    private val channelList = ArrayList<ChannelInfo>()

    private val tStart = HData(T_START)
    private val tEnd = HData(T_END)

    private val screenH
        get() = QMUIDisplayHelper.px2dp(this, QMUIDisplayHelper.getScreenHeight(this))

    private val screenW
        get() = QMUIDisplayHelper.px2dp(this, QMUIDisplayHelper.getScreenWidth(this))

    private val Float.scp get() = (screenH * this)

    private val Float.w: HData get() = HData(T_SPACE, this.toInt())
    private val Float.c: HData get() = HData(T_CLICK_CHECK, this.toInt())

    private var searchView: ImageView? = null
    private var isSearchPress = false

    var canScroll = true//是否可以滑动

    private fun RecyclerView.addManager(_canScroll: Boolean = false) {
        layoutManager = object : LinearLayoutManager(
            this@HHomeActivity,
            RecyclerView.HORIZONTAL, false
        ) {
            override fun canScrollHorizontally() = _canScroll or canScroll
        }
    }

    override fun initData() {
//        Player.init()
        QMUIStatusBarHelper.translucent(this)
        QMUIStatusBarHelper.setStatusBarDarkMode(this)
        com.lej.upgrade.checkUpgrade(this, true) { showGuideDialog() }
        lifecycleScope.launchWhenCreated {
            pushProvider?.pushMap(this@HHomeActivity)
        }

        viewModel.getHomeData().onSuccess(this) { list ->
            tStart.addElement()
            list.forEachIndexed { index, info ->
                when (info.type) {
                    CardType.LIVE -> HData(
                        T_LIVE,
                        liveInfo = info.liveInfo,
                        size = if (index == (list.size - 1)) -1 else 0
                    ).addElement()
                    CardType.WALL -> {
                        HData(T_NFT_WALL, individualInfo = info.individualInfo).addElement()
                        info.individualInfo?.nftList?.let {
                            it.forEach { nft -> HData(T_NFT, nftInfo = nft).addElement() }
                            val t =
                                ((wallW / channelList[0].vel * channelList[2].vel) - leftNft) - (it.size * nftW)
                            t.w.addElement(2)
                        }
                    }
                    CardType.BOOTH -> HData(T_BOOTH, boothInfo = info.boothInfo).addElement()
                    CardType.BANNER ->
                        HData(T_BANNER, bannerInfo = info.bannerInfo).addElement()
                }
            }
            if (list.last().type == CardType.LIVE) {
                tEnd.addElement()
            } else {
                (leftLive / channelList[0].vel * channelList[3].vel).c.addElement(3)
            }
            channelList.forEach { it.adapter.setList(it.data) }
        }
        binding.ivHead.onClick { showClickPop() }

        binding.rlvHomeList0.channelData(0.9f)
        binding.rlvHomeList1.channelData(1.2f)
        binding.rlvHomeList2.channelData(1.6f)
        binding.rlvHomeList3.channelData(1.0f, true)

        binding.rlvHomeList3.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                if (recyclerView.scrollState == RecyclerView.SCROLL_STATE_IDLE) return
                canScroll = true
                for (channelInfo in channelList) {
                    if (channelInfo.target == recyclerView) continue
                    channelInfo.px += dx * channelInfo.vel
                    val pxx = channelInfo.px.toInt()
                    channelInfo.px -= pxx
                    channelInfo.target.scrollBy(pxx, dy)
                }
            }
        })
    }


    /**
     * 点击头像
     */
    private fun showClickPop() {
        XPopup.Builder(this).hasShadowBg(false).hasStatusBar(false).hasNavigationBar(false)
            .atView(binding.ivHead).asCustom(object : AttachPopupView(this) {
                override fun getImplLayoutId(): Int {
                    return R.layout.home_popup_my_head
                }

                override fun initPopupContent() {
                    super.initPopupContent()
                    val binding =
                        HomePopupMyHeadBinding.bind(attachPopupContainer.findViewById(R.id.cl_pop))
                    binding.tvCard.onClick {
                        dismiss()
                        unityProvider?.openCard(this@HHomeActivity, PCacheInfo.userId)
                    }
                    binding.tvMsg.onClick {
                        dismiss()
                        unityProvider?.openChat(this@HHomeActivity)
                    }
                    binding.tvSetting.onClick {
                        dismiss()
                        router(CRouter.newmy) }
                }
            }).show()
    }


    private fun HData.addElement(channel: Int = -1) {
        when (type) {
            T_SPACE, T_CLICK_CHECK -> channelList.getOrNull(channel)?.data?.add(this)
            T_START -> {
                val channelInfo = channelList[0]
                channelInfo.data.add(this)
                val t = startW / channelInfo.vel
                channelList[1].apply { data.add((vel * t).w) }
                channelList[2].apply { data.add((vel * t).w) }
                channelList[3].apply { data.add((vel * t - leftLive - 0.01f * screenW).c) }
            }
            T_LIVE -> {
                val channelInfo = channelList[3]
                channelInfo.data.add(this)
                if (size != -1) {
                    channelInfo.data.add(leftLive.c)
                }
                val t = liveW / channelInfo.vel
                if (isSkip) {
                    channelList[0].apply { data.add((vel * t - leftWall).w) }
                    channelList[1].apply { data.add((vel * t).w) }
                    channelList[2].apply { data.add((vel * t).w) }
                } else {
                    isSkip = true
                    channelList[0].apply { data.add((vel * t - leftWall - (vel - 1) * screenW).w) }
                    channelList[1].apply { data.add((vel * t - (vel - 1) * screenW).w) }
                    channelList[2].apply { data.add((vel * t - (vel - 1) * screenW).w) }
                }
            }
            T_NFT_WALL -> {
                val channelInfo = channelList[0]
                channelInfo.data.add(HData(T_WALL_START))
                channelInfo.data.add(HData(T_WALL_CONTENT, wallInfo = individualInfo?.wall1))
                channelInfo.data.add(HData(T_WALL_CONTENT, wallInfo = individualInfo?.wall2))
                channelInfo.data.add(HData(T_WALL_END))

                channelInfo.data.add(leftWall.w)
                val t = wallW / channelInfo.vel
                channelList[1].apply { data.add((vel * t - leftBooth).w) }
                channelList[2].apply { data.add((leftNft).w) }
                channelList[3].apply { data.add((vel * t).c) }
            }
            T_NFT -> channelList[2].data.add(this)
            T_BOOTH -> {
                val channelInfo = channelList[1]
//                channelInfo.data.add(this)

                channelInfo.data.add(HData(T_BOOTH_START))
                boothInfo?.boothList?.forEachIndexed { index, it ->
                    it.isFirst = index == 0
                    channelInfo.data.add(HData(T_BOOTH_CONTENT, boothItem = it))
                }
                channelInfo.data.add(HData(T_BOOTH_END))


                val t = (boothInfo!!.getBoothW() - leftBooth) / channelInfo.vel
                channelList[0].apply { data.add((vel * t - leftBanner).w) }
                channelList[2].apply { data.add((vel * t).w) }
                channelList[3].apply { data.add((vel * t).c) }
            }
            T_BANNER -> {
                val channelInfo = channelList[0]
                channelInfo.data.add(this)
                val t = (bannerW - leftBanner) / channelInfo.vel
                channelList[1].apply { data.add((vel * t).w) }
                channelList[2].apply { data.add((vel * t).w) }
                channelList[3].apply { data.add((vel * t - leftLive).c) }
            }
            T_END -> {
                val channelInfo = channelList[0]
                channelInfo.data.add(this)
                val t = endW / channelInfo.velgenerateMultiQHolder
                channelList[1].apply { data.add((vel * t).w) }
                channelList[2].apply { data.add((vel * t).w) }
            }
        }
    }

    private fun RecyclerView.channelData(vel: Float, hasScroll: Boolean = false) {
        this.addManager(hasScroll)
        channelList.add(ChannelInfo(vel, this, this.bindAdapter()))
    }

    private fun RecyclerView.bindAdapter(): QuickMultiAdapter<HData> = generateMultiQHolder(
        MultiHolder(R.layout.home_item_click_listener, T_CLICK_CHECK) { h, item ->
            val view = h.itemView as? MoveView ?: return@MultiHolder
            view.layout_width = item?.size ?: 0
            view.setCheckList(binding.rlvHomeList2, binding.rlvHomeList1, binding.rlvHomeList0)
        },
        MultiHolder(R.layout.home_item_space, T_SPACE) { h, item ->
            h.getView<View>(R.id.space_view).layout_width = item?.size ?: 0
        },
        MultiHolder(R.layout.home_item_start, T_START, ::bindStart),
        MultiHolder(R.layout.home_item_end, T_END),
        liveHolder(),//艺术展馆
        MultiHolder(R.layout.home_item_house_wall_start, T_WALL_START),
        MultiHolder(R.layout.home_item_house_wall_content_new, T_WALL_CONTENT, ::bindWall),
        MultiHolder(R.layout.home_item_house_wall_end, T_WALL_END),
        singeNFTHolder(),//单个nft
        MultiHolder(R.layout.home_item_booth_list_left, T_BOOTH_START),
        MultiHolder(R.layout.home_item_booth_list_item_new, T_BOOTH_CONTENT, ::bindBooth),
        MultiHolder(R.layout.home_item_booth_list_right, T_BOOTH_END),

        adBannerHolder(),//广告banner
        getType = { it.type }, loadType = LOAD_TYPE_NONE
    )

    override fun onPause() {
        super.onPause()
        canScroll = false
    }

    override fun onResume() {
        super.onResume()
        viewModel.getUnreadMsg().addObserver {
            when (it) {
                is ResStatus.Success -> {
                    binding.ivUnreadNum.isVisible = it.data != 0
                    binding.ivUnreadNum.text = it.data.toString()
                }
                is ResStatus.Error -> binding.ivUnreadNum.isVisible = false
                is ResStatus.Loading -> {}
            }
        }
    }

    /**
     * 展示修改用户名
     */
    private fun showUpdateNickDialog(name: String) {
        if (!PCacheInfo.firstShowEditName || !name.startsWith("大有用户_")) return
        PCacheInfo.firstShowEditName = false
        HorAlertPopDialog.show(
            this,
            title = "提示",
            content = "系统已更新昵称修改功能，是否立即前往",
            confirmText = "立即前往",
            cancelText = "取消",
            autoSizeLayout = false,
            onConfirm = {
                router(CRouter.newmy) {
                    withInt(Params.INDEX, 0)
                }
            }
        )
    }

    /**
     * 首页的一些公告弹窗
     */
    private fun showGuideDialog() {
        if(!NetworkUtil.isWifi(this@HHomeActivity)){
            "当前为非Wi-Fi环境，请注意流量消耗".toast()
        }
        lifecycleScope.launch {
            val userInfoJob = async { viewModel.getUserInfo() }
            val noticeContent = async { viewModel.getActiveNotice(versionName) }
            userInfoJob.await()?.apply {
                PCacheInfo.imId = tencent_id ?: ""
                PCacheInfo.imToken = tencent_user_sig ?: ""
                PCacheInfo.userId = id
                PCacheInfo.isAuth = isAuthentication()
                PCacheInfo.nick = nick
                load(avatar.changeQiniuSize(100, 100), binding.ivHead)
                showUpdateNickDialog(nick)
            }
            val content = noticeContent.await()
            if (content.isNullOrEmpty()) return@launch
            showActiveNoticeDialog(content)
        }
    }

    /**
     * 展示活动弹窗
     */
    private fun showActiveNoticeDialog(content: String) {
        XPopup.Builder(this)
            .hasStatusBar(false)
            .asCustom(object : CenterPopupView(this) {
                override fun getImplLayoutId(): Int = R.layout.home_dialog_active_notice
                override fun initPopupContent() {
                    super.initPopupContent()
                    findViewById<TextView>(R.id.tv_content)?.text = content
                    findViewById<AppCompatImageView>(R.id.iv_close).onClick { dismiss() }
                }
            }).show()
    }

    //region itemHolder
    /**直播holder*/
    private fun liveHolder() =
        MultiHolder<HData>(R.layout.home_item_live_new, T_LIVE) { h, item ->
            val liveInfo = item?.liveInfo ?: return@MultiHolder
//            val player = h.getView<PlayerView>(R.id.iv_live_1)
//            player.playUrl(liveInfo.url ?: "")
            h.getBind<HomeItemLiveNewBinding>()?.apply {

                ivSpaceDetailInto.setImageResource(
                    if (liveInfo.isPreView()) {
                        if (liveInfo.action.isNullOrEmpty()) R.drawable.ic_home_live_none else R.drawable.ic_home_live_video
                    } else {
                        R.drawable.ic_home_live_into
                    }
                )
                moveCheck1.setCheckList(
                    binding.rlvHomeList2,
                    binding.rlvHomeList1,
                    binding.rlvHomeList0
                )
                moveCheck2.setCheckList(
                    binding.rlvHomeList2,
                    binding.rlvHomeList1,
                    binding.rlvHomeList0
                )
                load(liveInfo.url ?: "", ivLive1)
                flShowDetail.isInvisible = true  //详情介绍
                clAuthor.isVisible = true
                ivSpaceInto.isVisible = true
                tvAuthorName.text = liveInfo.nick ?: ""
                tvAuthorDesc.text = liveInfo.authorDesc ?: "" // 作者简介
                clLiveTag.isVisible = liveInfo.isLiving()
                load(liveInfo.head, ivAuthorIcon)
                load(R.drawable.iv_live_gif, ivLiveGif)
                liveInfo.detail?.let { it ->
                    val detailAdapter = SpaceDetailAdapter(R.layout.home_item_space_detail).apply {
                        setList(liveInfo.detail?.descList)
                    }
                    rvDetail.adapter = detailAdapter
                    it.imgUrl?.takeIf { it.isNotEmpty() }?.let { itt ->
                        val view = LayoutInflater.from(this@HHomeActivity).inflate(R.layout.home_foot_space_detail,null,false)
                        val ivImg = view.findViewById<AppCompatImageView>(R.id.iv_img)
                        ivImg.dimensionRatio("h,${it.imgWidth ?: 0}:${it.imgHeight ?: 0}")
                        load(itt, ivImg)
                        detailAdapter.addFooterView(view)
                    }
                    tvDetailTitle.text = it.title ?: ""
                }
                load(liveInfo.spaceTag, ivSpaceType) // 空间类型
                ivLive1.onClick {
                    clLiveTag.isVisible = false
                    clAuthor.isVisible = false
                    ivSpaceInto.isVisible = false
                    flShowDetail.isVisible = true
                    flShowDetail.bottomEnterAnim(300)
                }
                ivDetailExit.onClick {
                    if (!flShowDetail.isVisible) return@onClick
                    flShowDetail.bottomExitAnim(300) {
                        flShowDetail.isVisible = false
                        clLiveTag.isVisible = liveInfo.isLiving()
                        clAuthor.isVisible = true
                        ivSpaceInto.isVisible = true
                    }
                }
                ivSpaceDetailInto.onClick {
                    clickIntoSpace(liveInfo)
                }
                ivSpaceInto.onClick {
                    clickIntoSpace(liveInfo)
                }
            }
        }

    private fun HomeItemLiveNewBinding.clickIntoSpace(liveInfo: LiveInfo) {
        if (liveInfo.isPreView()) {//没有对应空间,进入预览
            if (liveInfo.action.isNullOrEmpty()) {
                "敬请期待".toast()
            } else {
                CommonDialog(this@HHomeActivity).showCommonDialog(content = "是否观看视频") {
                    PlayerActivity.start(this@HHomeActivity, liveInfo.action!!)
                }
            }
        } else {
            if (!userIsLogin()) {
                router(CRouter.login) { addClearFlag() }
                return
            }
            if(liveInfo.houseId == 79 || liveInfo.houseId == 951){  //仅针对音乐空间活动
                if (isLow6GConfiguration()){
                    CommonDialog(this@HHomeActivity).showCommonDialog(content = "检测到您的机型可能出现卡顿\n" +
                            "特邀您尝鲜试用PC端，体验更高清更流畅的演唱会", cancelText = "还想试试", confirmText = "抢先体验PC端", cancel = {
                        enterRoom(liveInfo.houseId)
                    }) {
                        lifecycleScope.launch {
                            val url = viewModel.getPCAddress(versionName)
                            url?.let {
                                val uri: Uri = Uri.parse(it)
                                val intent = Intent(Intent.ACTION_VIEW, uri)
                                startActivity(intent)
                            }
                        }
                    }
                }else{
                    enterRoom(liveInfo.houseId)
                }
            }else{
                if (isLowConfiguration()) { //低配置提示
                    llLowDevice.isVisible = true
                    return
                }
                enterRoom(liveInfo.houseId)
            }
        }
    }


    private fun bindStart(h: BaseViewHolder, item: HData?) {
        h.getBind<HomeItemStartBinding>()?.apply {
            searchView = ivSearch
            ivSearch.onClick {
                unityProvider?.openSearchView(this@HHomeActivity)
            }
        }
    }

    /**
     *
     */
    private fun bindWall(h: BaseViewHolder, item: HData?) {
        val wallInfo = item?.wallInfo ?: return
        h.getBind<HomeItemHouseWallContentNewBinding>()?.apply {
            includeView.onClick {
                if (isLowConfiguration()) { //低配置检测
                    clErrorTips.isVisible = true
                    ivErrorContent1.textRes = R.string.home_low_devices_tips_line
                    ivErrorContent1.vertical_bias = 0.75f
                    tvErrorAttention.isVisible = false
                    return@onClick
                }

                ivErrorContent1.textRes = R.string.home_space_none
                enterRoom(houseId = wallInfo.houseId)
//                clErrorTips.isVisible = true
//                viewModel.getUserStatus().onSuccess(this@HHomeActivity) {
//                    if (it) {
//                        enterRoom(houseId = wallInfo.houseId)
//                    } else {
//                        clErrorTips.isVisible = true
//                    }
//                }
            }
            clErrorTips.isVisible = false
            load(wallInfo.showUrl, iv)
            load(wallInfo.head, ivHead)
            load(wallInfo.tagType, ivFlag)
            tvUserName.text = wallInfo.nick
        }
    }

    private fun bindBooth(h: BaseViewHolder, item: HData?) {
        val booth = item?.boothItem ?: return
        h.getBind<HomeItemBoothListItemNewBinding>()?.apply {
            ivBoothTag.isVisible = booth.isFirst
            clShow.dimensionRatio("w,${booth.w}:${booth.h}")
            tvNftName.text = booth.nftName ?: ""
            tvNftDesc.text = booth.desc ?: ""
            load(booth.url, ivShowCover,booth.w,booth.h)
            load(booth.tagType, ivType)
        }
        h.itemView.onClick {
            unityProvider?.openShop(this@HHomeActivity,
                booth.shopType,
                booth.shopId,
                booth.goodsId,
                false)
        }
    }

    /**单个nft*/
    private fun singeNFTHolder() =
        MultiHolder<HData>(R.layout.home_item_nft_view_new, T_NFT) { h, item ->
            val nftInfo = item?.nftInfo ?: return@MultiHolder
            h.getBind<HomeItemNftViewNewBinding>()?.apply {
                ivNftDetail.dimensionRatio("w,${nftInfo.h}:${nftInfo.w}")
                load(nftInfo.showUrl, ivNftDetail)
                load(nftInfo.tag, ivType)
                tvNftName.text = nftInfo.name ?: ""
                tvNftDesc.text = nftInfo.desc ?: ""
//                tvNftName.drawableStart(getDrawableCompat(getTag(nftInfo.tag)))

                fun toShop(view: View) {
                    view.scopeLaunch {
                        unityProvider?.openShop(this@HHomeActivity,
                            nftInfo.shopType,
                            nftInfo.shopId,
                            nftInfo.goodsId,
                            nftInfo.isAvatar)
                    }
                }
                ivNftDetail.onClick(block = ::toShop)
                ivNftChassisDetail.onClick(block = ::toShop)
//                ivNftDetail.onClick {
////                    router(CRouter.nftDetail) {
////                        withInt(Params.NFT_ID, nftInfo.nftId)
////                    }
//                }
//                ivNftChassisDetail.onClick {
//                    if (nftInfo.nftId == 0) return@onClick
//                    router(CRouter.nftDetail) {
//                        withInt(Params.NFT_ID, nftInfo.nftId)
//                    }
//                }

            }
        }

    /**广告banner*/
    private fun adBannerHolder() =
        MultiHolder<HData>(R.layout.home_item_ad_banner, T_BANNER) { h, item ->
            val adInfo = item?.bannerInfo ?: return@MultiHolder
            h.getBind<HomeItemAdBannerBinding>()?.apply {
                load(adInfo.sideBanner?.url, ivSideLive)
                load(adInfo.banner?.url, ivBannerLive)
                ivBannerLive.onClick {
                    val banner = adInfo.banner
                    bannerClick(banner)
                }
                ivSideLive.onClick {
                    val sideBanner = adInfo.sideBanner
                    bannerClick(sideBanner)
                }
                tvBannerDes.text = adInfo.slogan ?: ""
//                val pos = IntArray(2)
//                ivBannerLive.viewTreeObserver.addOnScrollChangedListener {
//                    ivBannerLive.getLocationOnScreen(pos)
//                    KLog.e("sss", "ivBannerLive size:${pos[0]}--${pos[1]}")
//                }
            }
        }

    /**
     * banner点击
     */
    private fun bannerClick(sideBanner: ADItem?) {
        if (sideBanner?.type == BANNER_TYPE_SPACE) {
            intoPersonSpace()
        } else if (sideBanner?.type == BANNER_TYPE_LINK) {
            if ((sideBanner.action ?: "").isEmpty()) {
                return
            }
            toLink(sideBanner.action ?: "") {
                withBoolean(ORIENTATION_PORTRAIT, true)
            }
        }
    }

    /**
     * 进入个人空间
     */
    private fun intoPersonSpace() {
        viewModel.getPersonInfo().onSuccess(this) {
            if (it.list.isEmpty()) return@onSuccess
            val info = it.list.first()
            enterRoom(info.house_id)
        }
    }
    //endregion

    /**
     * 进入房间(需要提前检测)
     */
    private fun enterRoom(houseId: Int) {
        lifecycleScope.launch { unityProvider?.enter3DRoom(this@HHomeActivity, houseId, true) }
    }

    private fun getTag(type: Int) = when (type) {
        HomeTag.tNew -> R.drawable.icon_tag_new
        HomeTag.tHot -> R.drawable.icon_tag_hot
        HomeTag.tRare -> R.drawable.icon_tag_rare
        HomeTag.tTop1 -> R.drawable.icon_tag_top1
        HomeTag.tOfficial -> R.drawable.icon_tag_official
        HomeTag.tComing -> R.drawable.icon_tag_coming
        HomeTag.tArtist -> R.drawable.icon_tag_artist
        else -> R.drawable.icon_tag_new
    }
}